"""
语音识别客户端测试
"""
import requests
import json
import uuid
import threading
import sys
from pynput import keyboard
from urllib.parse import urljoin


class SpeechRecognitionClient:
    """语音识别客户端"""
    
    def __init__(self, server_url="http://localhost:30703"):
        self.server_url = server_url
        self.is_recording = False
        self.session_id = str(uuid.uuid4())
        self.should_stop_sse = False
        
        # 启动 SSE 连接
        self.sse_thread = threading.Thread(target=self._sse_listener, daemon=True)
        self.sse_thread.start()
    
    def _sse_listener(self):
        """SSE 监听（适配统一格式）"""
        try:
            with requests.get(
                urljoin(self.server_url, f"/stream/recognize/{self.session_id}"),
                stream=True,
                headers={"Accept": "text/event-stream"},
                timeout=None
            ) as response:
                current_event = None
                
                for line in response.iter_lines():
                    if self.should_stop_sse:
                        break
                    
                    if line:
                        line = line.decode('utf-8')
                        
                        # 解析事件类型
                        if line.startswith('event: '):
                            current_event = line[7:].strip()
                        
                        # 解析数据
                        elif line.startswith('data: '):
                            data = line[6:]
                            try:
                                result = json.loads(data)
                                
                                # 根据事件类型处理
                                if current_event == "start":
                                    # 连接建立（静默处理）
                                    pass
                                
                                elif current_event == "message":
                                    # 显示识别结果
                                    if result["type"] == "partial":
                                        sys.stdout.write(result["text"])
                                        sys.stdout.flush()
                                    elif result["type"] == "final":
                                        print(f"\n最终结果: {result['text']}")
                                        print("-" * 50)
                                
                                elif current_event == "ping":
                                    # 心跳事件（静默处理）
                                    pass
                                
                                elif current_event == "end":
                                    # 连接结束（静默处理）
                                    pass
                                
                                elif current_event == "error":
                                    # 错误处理
                                    print(f"\n❌ 错误: {result.get('message', '未知错误')}")
                            
                            except json.JSONDecodeError:
                                pass
        
        except Exception as e:
            if not self.should_stop_sse:
                print(f"\nSSE 错误: {e}")
    
    def start_recording(self):
        """开始录音"""
        try:
            response = requests.post(
                urljoin(self.server_url, f"/recording/start/{self.session_id}"),
                timeout=1
            )
            
            if response.status_code == 200:
                result = response.json()
                if result.get("code") == 200:
                    self.is_recording = True
                    sys.stdout.write("\n识别中: ")
                    sys.stdout.flush()
                else:
                    print(f"\n启动失败: {result.get('message')}")
        
        except Exception as e:
            print(f"\n启动录音失败: {e}")
    
    def stop_recording(self):
        """停止录音"""
        try:
            response = requests.post(
                urljoin(self.server_url, "/recording/stop"),
                timeout=1
            )
            
            if response.status_code == 200:
                result = response.json()
                if result.get("code") == 200:
                    self.is_recording = False
        
        except Exception as e:
            print(f"\n停止录音失败: {e}")
    
    def on_press(self, key):
        """按键按下"""
        if key == keyboard.Key.space and not self.is_recording:
            self.start_recording()
        try:
            if key.char == 'q':
                print("\n退出")
                self.should_stop_sse = True
                return False
        except AttributeError:
            pass
    
    def on_release(self, key):
        """按键释放"""
        if key == keyboard.Key.space and self.is_recording:
            self.stop_recording()
    
    def run(self):
        """运行客户端"""
        print("按住空格录音,按Q退出")
        print("正在连接服务器...")
        import time
        time.sleep(0.5)
        print("连接成功!")
        
        with keyboard.Listener(
            on_press=self.on_press,
            on_release=self.on_release
        ) as listener:
            listener.join()


if __name__ == "__main__":
    SpeechRecognitionClient().run()